// components/cpost/cpost.js
// 此处借鉴Axela 大佬的程序代码部分
const app = getApp();
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '',
    html: '',
    format: {},

  },
  lifetimes: {


  },
  /**
   * 组件的方法列表
   */
  methods: {
    async PostPub() {
      //信息上传
      const title = this.data.title.trim();
      const uinfo = wx.getStorageSync('wxuserinfo');
      const {
        html,
        text
      } = await this.getHTML();
      let cover = [];

      html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
        cover.push(capture)
      });

      if (!cover.length) {
        cover[0] = '';
      }
      //上传到云函数库
      wx.cloud.callFunction({
        name: 'kindb',
        data: {
          opr:'add',
          tablename:'DLOG',
          data:{
            title:title,
          html: html,
          uid:app.globalData.openid,
          cover: cover[0],
          type: '随笔',
          create_time: new Date().getTime(),
          uname:uinfo.nickName,
          uavatar:uinfo.avatarUrl,
          school:app.sel_item.name,
          parisenum:0,
          commentnum:0
          }
        }
      }).then(res => {
        this.editorCtx.clear()
        this.setData({
          title: ''
        })
        wx.showToast({
          title: '上传成功',
        })
  
        wx.navigateBack({
          delta: 1
        })
      })
    },
    getHTML() {
      return new Promise(reolve => {
        this.editorCtx.getContents({
          success(res) {
            reolve(res)
          }
        })
      })
    },
    //获取标题
    handleInputBlur(e) {
      this.setData({
        title: e.detail.value
      })
    },
    async insertImage() {
      let tempFilePaths = await this.chooseImage();
      wx.showLoading({
        title: '上传~',
      })
      this.uploadFile(0, tempFilePaths)
    },
    chooseImage() {
      return new Promise(reolve => {
        wx.chooseImage({
          count: 2,
          sizeType: ['compressed'],
          sourceType: ['album'],
          success: res => {
            reolve(res.tempFilePaths)
          }
        })
      })
    },
    //递归上传
    uploadFile(index, tempFilePaths) {
      const filePath = tempFilePaths[index];
      const timestamp = Date.parse(new Date());
      const cloudPath = 'blog/' + timestamp + filePath.match(/\.[^.]+?$/)[0]
      wx.cloud.uploadFile({
        cloudPath,
        filePath,
        success: f => {
          this.editorCtx.insertImage({
            src: f.fileID,
            width: '100%',
            success: () => {
              if (index == tempFilePaths.length - 1) {
                wx.hideLoading();
              }
            }
          })

          if (index < tempFilePaths.length - 1) {
            this.uploadFile(index + 1, tempFilePaths)
          }
        }
      })
    },
    //插入日期
    insertDate() {
      const date = new Date()
      const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
      this.editorCtx.insertText({
        text: formatDate
      })
    },
    formatstyle(e) {
      //配置文本形式
      let {
        name,
        value
      } = e.target.dataset
      if (!name) return
      this.editorCtx.format(name, value)
    },
    onEditorReady() {
      //编辑器准备完毕
      this.createSelectorQuery().select('#editor').context(res => {
        console.log(res)
        this.editorCtx = res.context
      }).exec()
    },
    onStatusChange(e) {
      //状态改变
      const format = e.detail
      this.setData({
        format
      })
    }

  }
})